package com.example.utils;

import com.example.common.CustomException;
import com.example.pojo.MailBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 发送邮件工具类
 *
 * @author czx
 * @since 2022/6/3 13:55
 */
@Component
@Slf4j
public class MailUtils {
    /**
     * 邮件发送者
     */
    @Value("${spring.mail.username}")
    private String MAIL_SENDER;

    /**
     * 注入发送邮件bean
     */
    @Resource
    private JavaMailSender mailSender;

    /**
     * 邮箱发送纯文本
     *
     * @param mailBean 接收邮件
     */
    public void sendText(MailBean mailBean) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(MAIL_SENDER);
        mailMessage.setTo(mailBean.getToEmail());
        mailMessage.setSubject(mailBean.getSubject());
        mailMessage.setText(mailBean.getCode().toString());
        mailSender.send(mailMessage);
    }

    public void sendHtml(MailBean mailBean){
        MimeMessage mimeMessage;
        try {
            mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setFrom(MAIL_SENDER);
            mimeMessageHelper.setTo(mailBean.getToEmail());
            mimeMessageHelper.setSubject(mailBean.getSubject());
            // 加true，只发送HTML页面里面的内容，不加则发送整个页面代码
            mimeMessageHelper.setText(mailBean.getCode(),true);
            // 邮件发送
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("邮件发送失败：{}",e.getMessage());
            throw new CustomException("邮件发送失败");
        }

    }

}
